package com.xbh.management.task;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xbh.common.constants.FileType;
import com.xbh.management.service.MinioService;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * 导出文件服务
 *
 * @param <M>
 */
public abstract class SuperExport<M> implements Callable {

    protected String[] TITLE;
    protected String TITLEName;
    protected Integer[] TITLELength;
    protected List<M> list;
    protected IPage<M> list1;
    protected int SHEET_MAX_ROWS = 1000000;

    private static Logger logger = LoggerFactory.getLogger(SuperExport.class);

    @Autowired
    private MinioService minioService;

    protected String core() {
        ByteArrayOutputStream outputStream = exportExcel();
        if (outputStream == null) {
            return null;
        }
        try {
            String fileName = TITLEName + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx";
            String f = minioService.putObject(fileName, outputStream, FileType.XLSX);
            return f;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public String call() throws Exception {
        return core();
    }

    protected abstract void handle(SXSSFRow dateRow,Integer i,CellStyle style);

    /**
     * 导入excel表格
     */
    public ByteArrayOutputStream exportExcel() {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        CellStyle titleStyle = createCellStyle(workbook, (short) 14, true);
        CellStyle style = createCellStyle(workbook, (short) 14, false);
        SXSSFSheet sheet = null;
        SXSSFRow row;
        int total = 0;
        int rowIndex = 1;
        int sheetIndex = 1;
        if (list.size()==0){
            sheet = workbook.createSheet(TITLEName + (sheetIndex++));
            //创建表头
            row = sheet.createRow(0);
            for (int j = 0; j <TITLE.length; j++) {
                createCell(row , j , TITLE[j] , titleStyle);
                sheet.setColumnWidth(j,TITLELength[j] * 256);
            }
        }else {
            for (int i = 0; i < list.size(); i++) {
                total++;
                if (total % SHEET_MAX_ROWS == 1) {
                    sheet = workbook.createSheet(TITLEName + (sheetIndex++));
                    //创建表头
                    row = sheet.createRow(0);
                    for (int j = 0; j < TITLE.length; j++) {
                        createCell(row, j, TITLE[j], titleStyle);
                        sheet.setColumnWidth(j, TITLELength[j] * 256);
                    }
                    rowIndex = 1;
                }
                row = sheet.createRow(rowIndex++);
                row.setHeightInPoints(24);
                handle(row, i, style);
            }
        }
        try {
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return outputStream;

    }

    /**
     * 创建单元格
     * @param row
     * @param num
     * @param value
     * @param style
     */
    protected void createCell(SXSSFRow row, int num, String value, CellStyle style) {
        SXSSFCell cell = row.createCell(num);
        cell.setCellStyle(style);
        if (StringUtils.isEmpty(value) || "null".equals(value)) {
            value = "";
        }
        cell.setCellValue(value);
    }

    /**
     * 创建字体
     *
     * @param workbook
     * @param fontSize 字体大小
     * @param bold     是否加粗
     * @return
     */
    private CellStyle createCellStyle(SXSSFWorkbook workbook, short fontSize, boolean bold) {
        //在对应的workbook中新建字体
        Font font = workbook.createFont();
        //字体微软雅黑
        font.setFontName("宋体");
        //设置字体大小
        font.setFontHeightInPoints(fontSize);
        font.setBold(bold);
        //新建Cell字体
        CellStyle style = workbook.createCellStyle();
        style.setFont(font);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;


    }


    public void setTITLE(String[] TITLE) {
        this.TITLE = TITLE;
    }

    public void setTITLEName(String TITLEName) {
        this.TITLEName = TITLEName;
    }

    public void setTITLELength(Integer[] TITLELength) {
        this.TITLELength = TITLELength;
    }

    public void setList(List list) {
        this.list = list;
    }
    public void setList1(IPage list) {
        this.list1 = list;
    }


}
